package com.example.lihongxuan.Service;

import com.example.lihongxuan.Control.DBConnection;
import com.example.lihongxuan.Entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    static Connection conn = null;
    static Statement st = null;
    static PreparedStatement ps = null;
    static ResultSet rs= null;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setUserpassword(request.getParameter("userpassword"));

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = response.getWriter();

        try {
            System.out.println(checkAccount(user));
            writer.println(checkAccount(user));
        } catch (Exception e){
            e.printStackTrace();
        }

    }
    public String checkAccount(User user) throws SQLException {
        conn = DBConnection.getConnection();
        String sql = "select userid from lihongxuan.user where username = ? and userpassword = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, user.getUsername());
        ps.setString(2, user.getUserpassword());
        rs = ps.executeQuery();
        if (rs.next()){
            return "账号正确";
        } else {
            return "账号密码错误";
        }
    }
}
